<template>
  <el-form ref="form"
           :model="form"
           :label-position="'top'"
           :rules="rules">
    <el-form-item
      :label="$t('config.business.title')"
      prop="title">
      <el-input v-model.trim="form.title"></el-input>
    </el-form-item>
    <el-form-item
      :label="$t('config.business.desc')"
      prop="desc">
      <el-input v-model.trim="form.desc"></el-input>
    </el-form-item>
    <el-form-item
      :label="$t('config.business.event')"
      prop="eventType">
      <el-radio-group v-model="form.eventType" class="radio" size="mini" @change="eventChange">
        <el-radio label="shift" name="shift">{{$t('configLazyLoad.businessConfig.workOrderTransferIn')}}</el-radio>
        <el-radio label="timeout" name="timeout">{{$t('configLazyLoad.businessConfig.workOrderTimeout')}}</el-radio>
        <el-radio label="back" name="back">{{$t('configLazyLoad.businessConfig.workOrderReturn')}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-row :gutter="20" v-if="form.eventType=='timeout'">
      <el-col :span="8">
        <el-form-item>
          <div class="time-out">
              <el-select v-model="form.timeoutEventConfig.timeoutType"
                style="width:100%"
                @change="timeoutTypeChange"
                :filterable="true">
                <el-option :label="$t('configLazyLoad.businessConfig.beforeTimeoutOccurs')" value="before"></el-option>
                <el-option :label="$t('configLazyLoad.businessConfig.whenTimeoutOccurs')" value="current"></el-option>
                <el-option :label="$t('configLazyLoad.businessConfig.afterTimeoutOccurs')" value="after"></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item  v-show="form.timeoutEventConfig.timeoutType!=='current'" prop="time">
          <div class="time-out">
              <el-input v-model.trim="form.timeoutEventConfig.time"></el-input>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item v-show="form.timeoutEventConfig.timeoutType!=='current'">
           <el-radio-group v-model="form.timeoutEventConfig.type" class="radio" size="mini">
              <el-radio-button label="min" name="min">{{$t('public.minutes2')}}</el-radio-button>
              <el-radio-button label="hours" name="hours">{{$t('public.hours2')}}</el-radio-button>
              <el-radio-button label="day" name="day">{{$t('public.day2')}}</el-radio-button>
            </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item
      :label="$t('config.business.triggerCondition')" v-if="form.eventType !== 'back'">
      <div slot="label">
        {{$t('config.business.triggerCondition')}} &nbsp;<span class="prompt">{{$t('config.business.triggerConditionTip')}}</span>
      </div>
      <!--添加删除交互组件-->
      <condition-ui :data="form.all"
                    ref="all"
                    :add="addCondition('all')"
                    :remove="remove('all')">
        <template slot="title">
          {{$t('config.business.allFollowingConditions')}}
        </template>
        <!--条件组件-->
        <trigger-condition slot="item"
                           slot-scope="props"
                           :item="props.item"
                           :allAgent="allAgent"
        ></trigger-condition>
      </condition-ui>
      <condition-ui :data="form.anyOne"
                    ref="anyOne"
                    :add="addCondition('anyOne')"
                    :remove="remove('anyOne')">
        <template slot="title">
          {{$t('config.business.anyFollowingConditions')}}
        </template>
        <!--条件组件-->
        <trigger-condition slot="item"
                           slot-scope="props"
                           :item="props.item"
                           :allAgent="allAgent"
        ></trigger-condition>
      </condition-ui>
    </el-form-item>
    <el-form-item 
      :label="$t('config.business.performOperations')">
      <condition-ui :data="form.actions"
                    :add="addOperate"
                    ref="actions"
                    :addDisabled="addTypes.length === 0"
                    :remove="remove('actions')">
        <!--操作组件-->
        <trigger-operate slot="item"
                         slot-scope="props"
                         :addTypes="addTypes"
                         :item="props.item"
                         v-bind="$attrs"
                         :currentStep="currentStep"
                         :eventType="form.eventType"
                         :mailTemplateList="mailTemplateList"
                         :mailId="mailId"
                         :appraiseTemplates="appraiseTemplates"
                         :allAgent="allAgent"></trigger-operate>
      </condition-ui>
    </el-form-item>
  </el-form>
</template>
<script>
  import triggerCondition from '../base/conditionItem'
  import triggerOperate from '../base/operateItem'
  import conditionUi from '../base/conditionUi'
  import {cloneDeep, uniqBy} from 'lodash'
  import {isHasMenu} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  import {parseIntTime, timeTrans} from '@/utils/workflowUtils'
  import API from '../../../../../store/api/config/emailNotify'
  // form默认值
  let baseForm = {
    title: '',
    desc: '',
    eventType: 'shift',
    all: [],
    state: 'run',
    anyOne: [],
    actions: [],
    timeoutEventConfig:{
      timeoutType:'current',
      time:'',
      type:'min'
    }
  }
  export default {
    name: 'trigger-form',
    data () {
      let self = this
      let validate = (rule, value, callback) => {
        if(self.form.timeoutEventConfig.timeoutType!=='current'&&!self.form.timeoutEventConfig.time){
          callback(new Error(this.$t('validate.required')))
        }else{
          if (checkform(self.form.timeoutEventConfig.time, 'Number5')) {
            callback(new Error(this.$t('configLazyLoad.businessConfig.mustBePositiveInteger')))
          } else if (self.form.timeoutEventConfig.timeoutType=='before'&&self.flowTime.seconds < parseIntTime(self.form.timeoutEventConfig.type, self.form.timeoutEventConfig.time)) {
            callback(new Error(this.$t('configLazyLoad.businessConfig.mustBeLessThanOrEqual')+self.flowTime.show))
          } else {
            callback()
          }
        }
      }
      return {
        form: cloneDeep(baseForm),
        itemForm: {
          assign: {type: 'assign', agent: '', leaveNot: false},
          sendSms: {type: 'sendSms', agent: [], notify: [], templateId: ''},
          sendSatisfaction: {type: 'sendSatisfaction', agent: '', notify: []},
          sendMessage: {type: 'sendMessage', agent: []},
          sendMail: {type: 'sendMail', mailType: ['stable'], to: [], cc: [], templateId: '', mailId: '', customTo: '', customCc: '', notify: []},
        },
        allAgent: [],
        appraiseTemplates: [],
        mailTemplateList: [],
        mailId: '',
        rules: {
          title: [{required: true, message: this.$t('validate.required'), trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value.length > 200) {
                  callback(new Error(this.$t('configLazyLoad.businessConfig.businessNameTip2')))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }],
          desc: [
            {
              validator: (rule, value, callback) => {
                if (value.length > 200) {
                  callback(new Error(this.$t('configLazyLoad.businessConfig.businessNameTip3')))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }],
          time: [
            {required: false, validator: validate, trigger: 'blur'}
          ]
        }
      }
    },
    props: {
      currentStep: {type: Object, default: function () { return {} }}
    },
    provide () {
      let arr = ['simple_notification_mail_config']
      return {
        powerList: arr.filter((item) => isHasMenu(item, this.$store.state.session.user))
      }
    },
    components: {
      triggerCondition,
      triggerOperate,
      conditionUi
    },
    computed: {
      // 不同情况，显示不同的操作
      operateTypes () {
        // 事件：工单转入
        if (this.form.eventType === 'shift' || this.form.eventType === 'back' ) {
          // 系统步骤
          if (this.currentStep.type === 'sys') {
            return ['sendMessage', 'sendSms', 'sendMail', 'sendSatisfaction']
          } else {
            if(this.form.eventType === 'back') return ['sendMessage', 'sendSms', 'sendMail']
            return ['assign', 'sendMessage', 'sendSms', 'sendMail']
          }
        } else {
          // 事件：超时提醒
          return ['sendMessage','sendSms', 'sendMail']
        }
      },
       // form中的操作类型
      formOperate () {
        return this.form.actions.map((item) => item.type)
      },
      // 可添加的操作
      addTypes () {
        return this.operateTypes.filter((item) => {
          return this.formOperate.indexOf(item) === -1
        })
      } ,
      flowTime () {
        let obj = {show: '', seconds: Infinity}
        if (this.currentStep.ctype && this.currentStep.ctime) {
          obj.show = timeTrans(this.currentStep.ctype, this.currentStep.ctime)
          obj.seconds = parseIntTime(this.currentStep.ctype, this.currentStep.ctime)
        }
        return obj
      }
    },
    methods: {
      submit () {
        let data = null
        let arr = ['all', 'anyOne', 'actions']
        if (!this.form.actions.length) {
          this.$message.error('请至少添加一条操作')
          return null
        }
        // 根据type类型去重
        let actions = uniqBy(this.form.actions, 'type')
        if (actions.length < this.form.actions.length) {
          this.$message.error('同一种操作，只能添加一次')
          return null
        }
        this.$refs.form.validate((valid) => {
          data = valid ? this.form : null
        })
        // 条件组件及操作组件的必填校验
        arr.forEach((item) => {
          if(this.$refs[item]){
            this.$refs[item].$children.forEach((one) => {
              if (!one.submit()) {
                data = null
              }
            })
          }
        })
        return data
      },
      eventChange () {
        this.form.actions = []
        this.form.all = []
        this.form.anyOne = []
      },
      addCondition (type) {
        let self = this
        return function () {
          self.form[type].push({type: 'fixedFields', fieldId: 'createUser', fieldName: [], condition: 'in', data: {}})
        }
      },
      initForm (data) {
        this.$refs.form.clearValidate()
        this.form = cloneDeep(baseForm)
        // this.$set(this,'from',baseForm)
        if (data) {
          for (let i in this.form) {
            for(let j in data){
              if(i == j){
                this.form[i] = cloneDeep(data[j]) 
              }
            }
          }
          this.form.actions.forEach((item) => {
            if (item.type === 'sendMail') {
              item.customTo = item.customTo.join(';')
              item.customCc = item.customCc.join(';')
            }
          })
          this.form.triggerId = data.triggerId
        if(data.all&&data.all[0]){
          setTimeout(()=>{
            this.form.all = [...data.all]
          },1) 
        }
        }
      },
      addOperate () {
        // 系统步骤，没有分配座席
        // 工单超时事件只有短信操作
        if (!this.addTypes.length) {
          return
        }
        let itemType = this.addTypes[0]
        if (itemType) {
           this.form.actions.push(cloneDeep(this.itemForm[itemType]))
        }
      },
      // 删除条件或操作
      remove (type) {
        let self = this
        return function (index) {
          self.form[type].splice(index, 1)
        }
      },
      //超时类型选择
      timeoutTypeChange(){
        this.form.timeoutEventConfig.time = ''
        this.$refs.form.fields.map(i =>{
          if(i.prop ==='time'){
            i.clearValidate()
          }
        })
      }
    },
    beforeMount () {
      this.allAgent = this.$getCache('agents').filter((item) => {
        return item.status === 'enable'
      }).map((item) => {
        return {key: item._id, name: `${item.displayName}[${item.exten}]`}
      })
      this.$store.dispatch('getAppraiseTemplates', {}).then((res) => {
        if (res.success) {
          this.appraiseTemplates = res.data
        }
      })
      // 获取邮件模版list
      API.queryEmailTemplateList({}).then((res) => {
        this.mailTemplateList = res.data
      })
      // 获取企业邮箱
      API.queryEmailList({}).then((res) => {
        if (res.data) {
          this.mailId = res.data[0] && res.data[0]._id
        }
      })
    }
  }
</script>

<style scoped lang='stylus'>
@import '../../../../../assets/common.styl'
.prompt
  color $c-prompt
</style>
